package com.shipwe.loans.utils.helper

import com.shipwe.loans.MyApps
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.HttpHelper
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/20 15:49
 * @Annotation：用户积分
 */
object UserPointsHelper {

    /**
     * 获取保存的签到数据
     */
    fun getUserSignInfoData(): JSONObject {
        val signData = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_SIGN_INFO)
        if (signData.isEmpty()){
            return JSONObject()
        }
        return JSONObject(signData)
    }

    /**
     * 获取用户当前积分数 (从签到信息中获取)
     */
    fun getShipweUserPoints(): Int{
        val signData = getUserSignInfoData()
        if (!signData.has("currScore")){
            return 0
        }
        return signData.optInt("currScore",0)
    }

    /**
     * 保存、使用 用户积分
     */
    fun onSaveUserPointsAction(useType: String,useInfo: String,points: String,callback: IHttpCallback? = null){
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.SHIPWE_API_SAVE_OR_USE_PATH)
            put("mobile", ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_MOBILE))
            put("scoreUseType",useType)//分数使用类型
            put("scoreUseInfo", useInfo)//分数使用说明 , 积分列表展示
            put("score", points)//增加传正数，减少传负数
        }
        HttpHelper.post(httpUrl,params,"",object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                callback?.onRequestSuccess(data)
                when(data.optInt("code")) {
                    0 -> {//成功
                        //积分存、去成功  需要刷新签到信息
                        MyApps.app.publisher.publish(AppEventData(AppEventData.TYPE.SHIPWE_POINTS_REFRESH))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                callback?.onRequestError(error)
            }

            override fun onRequestFinish() {
                callback?.onRequestFinish()
            }
        })
    }
}